<?php

namespace App\Http\Controllers;

use App\RBAC\Category;
use App\RBAC\Article;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;

class BlogController extends Controller
{
 
     /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth')->only('writer');
    }


    public function home(Request $request)
    {
        return view('home');
    }

    public function index(Request $request){
        $per_page=10;
        $page=1;
        if($request->page){
            $page=$request->page;
        }
        $data=[];
        $user=Auth::user();
        if($user){
            $data['categories']=$user->categories;   
        }else{
            $data['categories']=Category::where('user_id',1)->get();
        }
        $post=null;
        if($request->id){
            $post=Article::find($request->id);
            if($post){
                $count=Article::where('status','published')->where('id','>=',$post->id)->orderBy('id',"DESC")->count();
                $page=ceil($count/$per_page);
                //echo $count,'____',$page;exit();
                $request->offsetSet('page',$page);
            }
        }

        $cat=0;
        if($request->cat){
            $data['posts']=Article::where('status','published')->where('category_id',$request->cat)->orderBy('id',"DESC")->paginate($per_page);
            $data['cat']=$request->cat;
        }else{
            $data['posts']=Article::where('status','published')->orderBy('id',"DESC")->paginate($per_page);
        }
        
        if(!$post){
            if($request->cat){
                $post=Article::where('status','published')->where('category_id',$request->cat)->orderBy('id',"DESC")->skip($per_page*($page-1))->take(1)->first();
            }else{
                $post=Article::where('status','published')->orderBy('id',"DESC")->skip($per_page*($page-1))->take(1)->first();
            }
        }
        $data['post']=$post;
        $data['page']=$page;
        return view('pure',$data);
    }

     public function writer(Request $request){
        $data['hiddenNav']=true;
        return view('writer',$data);
    }



    
}
